//
//  UserRegistViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/8/21.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "UserRegistViewController.h"
#import "RentVieitor.h"
#import "AFNetworking.h"
#import "LCMD5Tool.h"
#import "GetPassWorldViewController.h"
#import "RegisterViewController.h"

@interface UserRegistViewController ()<UITextFieldDelegate>

@end

@implementation UserRegistViewController {
    
    MBProgressHUD *HUD;
    UIButton *loginBtn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatLeftView];
    [self creatView];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [SVProgressHUD dismiss];
}

- (void)creatLeftView {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 64)];
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(15, 20+12, 100,30);
    [leftBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 10, 70)];
    [leftBtn setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    //    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    //    self.navigationItem.leftBarButtonItem = leftItem;
    [view addSubview:leftBtn];
    [self.view addSubview:view];
    // 自定义导航栏左侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(KWidth-65, 20+10, 50, 20);
    [rightBtn setTitle:@"注册" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor colorWithRed:99/255.0 green:99/255.0 blue:99/255.0 alpha:1] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
    //    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    //    self.navigationItem.rightBarButtonItem = rightItem;
    [view addSubview:rightBtn];
    
}


- (void)creatView {
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20+64,KWidth-40 , 20)];
    titleLabel.text = @"账号密码登录";
    titleLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:titleLabel];
    
    NSArray *plaArray = @[@"请输入手机号",@"请输入密码"];
    for (int i=0; i<plaArray.count; i++) {
        
        UITextField *numText = [[UITextField alloc] initWithFrame:CGRectMake(20,50*(i+1)+5+64, KWidth-40, 40)];
        numText.placeholder = plaArray[i];
        numText.delegate = self;
        numText.tag = 100+i;
        numText.font = [UIFont systemFontOfSize:15];
        [self.view addSubview:numText];
        if (i==1) {
            numText.secureTextEntry = YES;
        }
        CALayer *lineLayer2 = [CALayer layer];
        lineLayer2.backgroundColor = [[UIColor colorWithRed:217/255.0 green:217/255.0 blue:217/255.0 alpha:1] CGColor];
        lineLayer2.frame = CGRectMake(20 ,50*(i+2)+64, KWidth-40, 1);
        [self.view.layer addSublayer:lineLayer2];
        
    }
    
    //登录
    loginBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    loginBtn.frame = CGRectMake(20, 20+150+64, KWidth-40, 40);
    [loginBtn setBackgroundColor:[UIColor colorWithRed:249/255.0 green:105/255.0 blue:39/255.0 alpha:1]];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.layer.masksToBounds = YES;
    [loginBtn addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    loginBtn.layer.cornerRadius = 2;
    [self.view addSubview:loginBtn];

    CALayer *MlineLayer = [CALayer layer];
    MlineLayer.backgroundColor = [[UIColor colorWithRed:217/255.0 green:217/255.0 blue:217/255.0 alpha:1] CGColor];
    MlineLayer.frame = CGRectMake((KWidth-1)/2 ,227.5+64, 1, 15);
    [self.view.layer addSublayer:MlineLayer];
    
    UIButton *userButton = [UIButton buttonWithType:UIButtonTypeSystem];
    userButton.frame = CGRectMake(20 , 225+64, KWidth/2-20-10 , 20);
    [userButton setTitleColor:[UIColor colorWithRed:99/255.0 green:99/255.0 blue:99/255.0 alpha:1] forState:UIControlStateNormal];
    userButton.titleLabel.font = [UIFont systemFontOfSize:13];
    userButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    userButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [userButton setBackgroundColor:[UIColor clearColor]];
    [userButton setTitle:@"手机快捷登录" forState:UIControlStateNormal];
    [userButton addTarget:self action:@selector(phoneAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:userButton];
    
    UIButton *forgetButton = [UIButton buttonWithType:UIButtonTypeSystem];
    forgetButton.frame = CGRectMake(KWidth/2+10 , 225+64, KWidth/2-20-10 ,20);
    [forgetButton setTitleColor:[UIColor colorWithRed:99/255.0 green:99/255.0 blue:99/255.0 alpha:1] forState:UIControlStateNormal];
    forgetButton.titleLabel.font = [UIFont systemFontOfSize:13];
    forgetButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    forgetButton.titleEdgeInsets = UIEdgeInsetsMake(0,0, 0, 0);
    [forgetButton setBackgroundColor:[UIColor clearColor]];
    [forgetButton setTitle:@"忘记密码" forState:UIControlStateNormal];
    [forgetButton addTarget:self action:@selector(forgetAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetButton];
    
    
    
}

//忘记密码
- (void)forgetAction {
    
    GetPassWorldViewController *getVc = [[GetPassWorldViewController alloc] init];
    [self presentViewController:getVc animated:YES completion:nil];
}

//手机快捷登录
- (void)phoneAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//登录
- (void)loginAction {
    
    
    loginBtn.enabled = NO;
    UITextField *userName = (UITextField *)[self.view viewWithTag:100];
    UITextField *passWorld = (UITextField *)[self.view viewWithTag:101];
    NSString *request = [self valiMobile:userName.text];
    if (request != nil) {
        
        loginBtn.enabled = YES;
        [APPDELEGATE showPro:@"手机格式不正确"];
        return;
    }
    
    if (passWorld.text.length<6 ) {
        
        loginBtn.enabled = YES;
        [APPDELEGATE showPro:@"请输入正确密码"];

        return;
    }
    
    [SVProgressHUD show];
    NSString *urlstr= @"http://api2.zuke.com/login/pwd";
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@%@",userName.text,passWorld.text,APPKEY_URL,urlstr];
    //32位小写
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSDictionary *param = @{
                            @"mobile":userName.text,
                            @"passwd":passWorld.text,
                            @"sign":md5String
                            };
    
    __weak typeof(self)weakSelf = self;
    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    manger.responseSerializer=[AFHTTPResponseSerializer serializer];
    manger.requestSerializer.timeoutInterval= 60;
    [manger POST:urlstr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [SVProgressHUD dismiss];
        loginBtn.enabled = YES;
        NSDictionary* jsonDic = [NSJSONSerialization
                                 JSONObjectWithData:responseObject
                                 options:kNilOptions
                                 error:nil];
        
        if ([jsonDic[@"code"] isEqualToString:@"10000"]) {
            
            //登录成功
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            NSDictionary *dataDic = jsonDic[@"data"];
            dataDic = [Utils nullDic:dataDic];
            [defaults setObject:dataDic forKey:User_listsKey];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:nil userInfo:nil];
            
            if ([weakSelf respondsToSelector:@selector(presentingViewController)]) {
                
                [weakSelf.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil]; // for IOS 5+
                
            } else {
                
                [weakSelf.parentViewController.parentViewController dismissViewControllerAnimated:YES completion:nil]; // for pre IOS 5
                
            }

        }else {
            
            [SVProgressHUD dismiss];
            [APPDELEGATE showPro:jsonDic[@"message"]];
            
        }
        

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        loginBtn.enabled = YES;
        [APPDELEGATE showPro:@"网络错误"];
        
    }];
}

- (void)backAction {
    
    if ([self respondsToSelector:@selector(presentingViewController)]) {
        
        [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil]; // for IOS 5+
        
    } else {
        
        [self.parentViewController.parentViewController dismissViewControllerAnimated:YES completion:nil]; // for pre IOS 5
        
    }
}

- (void)registerAction {
    
    RegisterViewController *regVc = [[RegisterViewController alloc] init];
    [self presentViewController:regVc animated:YES completion:nil];
}

//验证手机号
- (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"手机号长度只能是11位";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入正确的电话号码";
        }
    }
    return nil;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
@end
